import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, getUserInfo, logout } from '@/api/user'
import type { LoginForm, UserInfo } from '@/types/user'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo>({
    id: 0,
    username: '',
    nickname: '',
    email: '',
    avatar: '',
    role: 'user',
    status: 1,
    createTime: '',
    updateTime: ''
  })

  // 计算属性
  const isAdmin = computed(() => userInfo.value.role === 'admin')
  const isLoggedIn = computed(() => !!token.value)

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {
      id: 0,
      username: '',
      nickname: '',
      email: '',
      avatar: '',
      role: 'user',
      status: 1,
      createTime: '',
      updateTime: ''
    }
  }

  // 登录
  const loginAction = async (loginForm: LoginForm) => {
    try {
      const response = await login(loginForm)
      const { token: newToken, userInfo: info } = response.data

      setToken(newToken)
      setUserInfo(info)

      ElMessage.success('登录成功')

      // 获取重定向路径
      const redirect = router.currentRoute.value.query.redirect as string
      await router.push(redirect || '/')

      return Promise.resolve()
    } catch (error: any) {
      ElMessage.error(error.message || '登录失败')
      return Promise.reject(error)
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      setUserInfo(response.data)
      return Promise.resolve(response.data)
    } catch (error: any) {
      ElMessage.error(error.message || '获取用户信息失败')
      return Promise.reject(error)
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出接口调用失败:', error)
    } finally {
      clearToken()
      clearUserInfo()
      await router.push('/login')
      ElMessage.success('已退出登录')
    }
  }

  // 更新用户信息
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    userInfo.value = { ...userInfo.value, ...updates }
  }

  return {
    // 状态
    token,
    userInfo,

    // 计算属性
    isAdmin,
    isLoggedIn,

    // 方法
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    login: loginAction,
    getUserInfo: getUserInfoAction,
    logout: logoutAction,
    updateUserInfo
  }
})